/**
 * 
 */
package com.redside.webapp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.WebUtils;

import com.redside.Constants;
import com.redside.model.Role;
import com.redside.model.User;
import com.redside.service.ComplaintManager;
import com.redside.service.OptionsBeanLookupManager;
import com.redside.view.ActionItemsForm;

/**
 * @author <a href="mailto:pchapman@easystreet.net">Peter Chapman</a>
 *
 */
public class ActionItemsFormController extends BaseFormController{
    private final Log logger = LogFactory.getLog(ActionItemsFormController.class);

    public ActionItemsFormController() {
        setCommandName("actionItemsForm");
        setCommandClass(ActionItemsForm.class);
    }

    private ComplaintManager complaintManager;
    private OptionsBeanLookupManager optionsBeanManager;

    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        // set the county based on the logged in user
        ActionItemsForm actionItemsForm = new ActionItemsForm();
        User user = null;
        if(WebUtils.getSessionAttribute(request, "user") == null){
            Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(obj instanceof User){
                user=(User)obj;
                WebUtils.setSessionAttribute(request, "user", user);
                
            }
        }else{
            user=(User)WebUtils.getSessionAttribute(request, "user");
        }
        String ROLE = "";
        for (Role role : user.getRoles()) {
            logger.debug("-->Authority from userDetails: " + role.getName());
            ROLE = role.getName();
        }
        if (WebUtils.hasSubmitParameter(request, "countyId")) {
            actionItemsForm.setCountyId((String) request.getParameter("countyId"));
        } else if (StringUtils.equalsIgnoreCase(ROLE, Constants.USER_ROLE)) {
            actionItemsForm.setCountyId(user.getAddress().getCountyId());
        } else {
            actionItemsForm.setCountyId("0");
        }
        logger.debug("------------------->UserName from userDetails: "+user.getUsername());
        logger.debug("------------------->actionItemForm: "+actionItemsForm.toString());
        logger.debug("------------------->successview: "+getSuccessView());
        logger.debug("------------------->countyId (0 if all): "+actionItemsForm.getCountyId());
        return actionItemsForm;
    }

    public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
            Object command, BindException errors) throws Exception {
        ActionItemsForm form = (ActionItemsForm) command;
        RedirectView redirectView = new RedirectView(getSuccessView());
        redirectView.addStaticAttribute("countyId", form.getCountyId());
        return new ModelAndView(redirectView);
    }

    protected Map<String, List<?>> referenceData(HttpServletRequest request) throws Exception {
        User user = (User)WebUtils.getSessionAttribute(request, "user");
        String ROLE="";
        String COUNTY_ID="";
        for (Role role : user.getRoles()) {
            if(role.getName().equals(Constants.ADMIN_ROLE)){
            	ROLE = role.getName();
            	break;
            }
            if(role.getName().equals(Constants.USER_ROLE)){
            	ROLE = role.getName();
            	break;
            }
        }
        if (WebUtils.hasSubmitParameter(request, "countyId")) {
            COUNTY_ID = request.getParameter("countyId");
        } else if (StringUtils.equalsIgnoreCase(ROLE, Constants.ADMIN_ROLE)) {
            COUNTY_ID = "0";
        } else {
            COUNTY_ID = user.getAddress().getCountyId();
        }
        logger.debug("What county: "+COUNTY_ID);
        Map<String, List<?>> actionItems = new HashMap<String, List<?>>();
        actionItems.put("countyList", optionsBeanManager.findAll(Constants.COUNTY_LIST, "0",
                "All Counties"));
        logger.debug("countySize: "+actionItems.get("countyList").size());
        if (StringUtils.equalsIgnoreCase(ROLE, Constants.ADMIN_ROLE)
                && StringUtils.equalsIgnoreCase(COUNTY_ID, "0")) {
            actionItems.put("complaintList", complaintManager.findAllUnverified());
/*            actionItems.put("complainantIRLNotSent", complaintManager.findUnsentIRL(
                    Constants.CORR_TYPE_COMPLAINANT, "crlForAdminView"));
            actionItems.put("businessIRLNotSent", complaintManager.findUnsentIRL(
                    Constants.CORR_TYPE_IRL, "irlForAdminView"));
            actionItems.put("siteVisitByCounty", complaintManager.siteVisitByCountyId("0"));
            actionItems.put("citations", complaintManager
                    .findCitationComplaintsByCountyId("0"));
            actionItems.put("remediations", complaintManager.findAllRemediations());*/
        }
        if ((StringUtils.equalsIgnoreCase(ROLE, Constants.ADMIN_ROLE))
                && !StringUtils.equalsIgnoreCase(COUNTY_ID, "0")) {
        	actionItems.put("complaintList", complaintManager.findUnverifiedByCountyId(COUNTY_ID));
/*            actionItems.put("complainantIRLNotSent", complaintManager.findUnsentIRL(
                    COUNTY_ID, Constants.CORR_TYPE_COMPLAINANT, "crlByCounty"));
            actionItems.put("businessIRLNotSent", complaintManager.findUnsentIRL(COUNTY_ID,
                    Constants.CORR_TYPE_IRL, "irlByCounty"));
            actionItems.put("siteVisitByCounty", complaintManager
                    .siteVisitByCountyId(COUNTY_ID));
            actionItems.put("citations", complaintManager
                    .findCitationComplaintsByCountyId(COUNTY_ID));
            actionItems.put("remediations", complaintManager
                    .findRemediationByCountyId(COUNTY_ID));*/
        }
        logger.debug("returning action items..."+actionItems.size());
        return actionItems;
    }

    public void setComplaintManager(ComplaintManager complaintManager) {
        this.complaintManager = complaintManager;
    }

    public void setOptionsBeanManager(OptionsBeanLookupManager optionsBeanManager) {
        this.optionsBeanManager = optionsBeanManager;
    }

}
